
let {mat4} = require('gl-matrix');

// positions
// uvs
let positions = [
    -1,1,0,
    -1,-1,0,
    1,-1,0,
    1,1,0
];

let uvs = [
    0,1,
    0,0,
    1,0,
    1,1
];

let indices = [0,1,2,0,2,3];

let tmpMat = mat4.create();

class ScreenItem{

    constructor(shaderInfo) {
        this.shaderInfo = shaderInfo;

        let gl = globalThis.app.gl;
        let vao  = this.vao = gl.createVertexArrayOES();
        gl.bindVertexArrayOES(vao);

        let posVBO = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER,posVBO);
        gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(positions),gl.STATIC_DRAW);
        gl.enableVertexAttribArray(shaderInfo.attribs['a_position']);
        gl.vertexAttribPointer(shaderInfo.attribs['a_position'],3,gl.FLOAT,false,0,0);

        //
        let uvVBO = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER,uvVBO);
        gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(uvs),gl.STATIC_DRAW);
        gl.enableVertexAttribArray(shaderInfo.attribs['a_uv']);
        gl.vertexAttribPointer(shaderInfo.attribs['a_uv'],2,gl.FLOAT,false,0,0);

        // indices
        let indiceVBO = gl.createBuffer();
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,indiceVBO);
        gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,new Uint16Array(indices),gl.STATIC_DRAW);

        gl.bindVertexArrayOES(null);
    }

    render(camera,texId){
        let gl = globalThis.app.gl;
        let shaderInfo = this.shaderInfo;
        gl.useProgram(shaderInfo.program);
        gl.activeTexture(gl.TEXTURE0);
        gl.bindTexture(gl.TEXTURE_2D,texId);
        gl.uniform1i(shaderInfo.uniforms['u_sampler0'],0);

        gl.uniformMatrix4fv(shaderInfo.uniforms['projMatrix'],false,tmpMat);

        gl.bindVertexArrayOES(this.vao);
        gl.drawElements(gl.TRIANGLES,6,gl.UNSIGNED_SHORT,0);
        gl.bindVertexArrayOES(null);
        gl.useProgram(null);
    }

}

module.exports = ScreenItem;
